package com.wanyu.video.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOSelectorServerDemo {

    public static void main(String[] args) throws IOException {

        //创建一个ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 创建一个Selector
        Selector selector = Selector.open();

        //绑定端口并在服务端进行监听
        serverSocketChannel.socket().bind(new InetSocketAddress(10086));

        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        // 把ServerSocketChannel注册到selector， 事件为连接
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 等待客户端连接
        while(true){
            // 监听是否存在事件发生
            if(selector.select(1000) == 0){
                System.out.println("服务器等待 1s， 暂时无连接");
                continue;
            }
            // 存在事件发生，获取所有事件集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            // 获取迭代器进行循环查询事件
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

            while(keyIterator.hasNext()){
                SelectionKey selectionKey = keyIterator.next();
                // 通过事件监听判断是否存在连接请求，存在则进行连接
                if(selectionKey.isAcceptable()){

                    ServerSocketChannel registerServerChannel = (ServerSocketChannel)selectionKey.channel();
                    // 服务端开始接受连接
                    SocketChannel socketChannel = registerServerChannel.accept();
                    socketChannel.configureBlocking(false);
                    // 将socketChannel注册到selector,关注时间为OP_READ, 同时关联一个Buffer。
                    // 客户端发起连接之后，发生数据传输，这时候socketChannel将由selector进行监听
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if(selectionKey.isReadable()){
                    // 通过key反向获取到channel
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                    channel.read(buffer);
                    System.out.println("客户端输入数据： " + new String(buffer.array()));
                }
                // 从集合中删除当前selectionKey,防止重复操作
                keyIterator.remove();
            }
        }
    }
}
